/** 
 * @ClassName: DicParamDao 
 * @Description:  绯荤粺閰嶇疆琛?
 * @author 832
 * @date 2016骞?10鏈?11鏃? 
 *  
 */
package com.fzrskj.cloud.free.dic.dao;

import com.fzrskj.cloud.free.core.tool.CObjectTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.core.utils.CloudDbDrvUtils;
import com.fzrskj.cloud.free.core.utils.EncryptHelper;
import com.fzrskj.cloud.free.core.utils.EncryptUtils;
import com.fzrskj.cloud.free.dic.bean.DicParam;
import ms.core.consts.SysErr;
import ms.core.db.IDbDrv;
import ms.core.object.CObject;
import ms.core.tool.StrTool;

import java.util.List;
import java.util.Map;
import java.util.ArrayList;

public class DicParamDao extends CObject{
	//private declarations
	private IDbDrv db=null;

	//constructor function to initialize database access object
	public DicParamDao(){
		db= CloudDbDrvUtils.getDbUtilsDrv();
	}

	//to free resource
	@Override
	public void dispose(){
		db.closeConnection();
	}

	public List<DicParam> getListDicParam(int paramType) {
		return this.getListDicParam(paramType, null);
	}

	/**
	 * 获取系统配置中的参数
	 * @param paramType
	 * @return
	 */
	public List<DicParam> getListDicParam(int paramType, String startFrom) {
		String sql = "select * from dic_param where paramType=? ";
		List<Object> args = new ArrayList<>();
		args.add(paramType);

		if (paramType == 1 || paramType == 3){
			sql += " and agentId=? ";
			args.add(CloudContextUtils.getAgentId());
		}

		if (!StrTool.isBlankStr(startFrom)) {
			sql += " and paramName like ? ";
			args.add(startFrom + "%");
		}
		List<DicParam> list = db.queryForBeans(sql, DicParam.class, args.toArray());
		String code = db.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			this.log(db.getMsg());
		}
		this.setErrCode(code);
		if (null != list) {
			list.forEach(item -> {
				if (!StrTool.isBlankStr(item.getParamName()) && EncryptHelper.encryptSysParam.contains(item.getParamName())) {
					item.setParamValue(EncryptUtils.decodeSave(item.getParamValue()));
				}
			});
		}
		return list;
	}

	/**
	 * 更新系统配置参数
	 *
	 * @param paramValue
	 * @param paramName
	 * @param paramType
	 * @return
	 */
	public int uptDicParam(String paramValue, String paramName, int paramType) {
		if (EncryptHelper.encryptSysParam.contains(paramName) && !StrTool.isBlankStr(paramValue)) {
			paramValue = EncryptUtils.encodeSave(paramValue);
		}
		String sql = "update dic_param set paramValue=? where paramName=? and paramType=? ";
		Object[] params = {paramValue, paramName, paramType};
		if (paramType == 1 || paramType == 3){
			sql += " and agentId=? ";
			params = CObjectTool.objectArrAddValue(params, CloudContextUtils.getAgentId());
		}
		int ret = db.executeSql(sql, params);
		String code = db.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			this.log(db.getMsg());
		}
		this.setErrCode(code);
		return ret;
	}

	/**
	 * 通过name与属性查询数值
	 *
	 * @param paramName
	 * @param paramType
	 * @return
	 */
	public String getParamValue(String paramName, int paramType) {
		String sql = "select paramValue from dic_param where paramName=? and paramType=? ";
		Object[] params = {paramName, paramType};
		if (paramType == 1 || paramType == 3){
			sql += " and agentId=? ";
			params = CObjectTool.objectArrAddValue(params, CloudContextUtils.getAgentId());
		}
		String str = (String) db.queryFieldValue(sql, String.class, params, 1);
		String code = db.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			this.log(db.getMsg());
		}
		this.setErrCode(code);
		if (!StrTool.isBlankStr(str) && EncryptHelper.encryptSysParam.contains(paramName)) {
			str = EncryptUtils.decodeSave(str);
		}
		return str;
	}

	/**
	 * 通过name与属性查询数值
	 *
	 * @param paramName
	 * @return
	 */
	public String getParamValue(String paramName) {
		return this.getParamValue(paramName, CloudContextUtils.getAgentId());
	}


	/**
	 * 通过name与属性查询数值
	 *
	 * @param paramName
	 * @return
	 */
	public String getParamValue(String paramName, Integer agentId) {
		String sql = "select paramValue from dic_param where paramName=? and ((agentId=? and (paramType=1 or paramType=3)) " +
				" or (agentId=0 and paramType=2 and paramName not in (select paramName from dic_param where agentId=? and paramType!=2))) ";
		Object[] params = {paramName, agentId, agentId};
		Object fieldResult = db.queryFieldValue(sql, String.class, params, 1);
		String str = null == fieldResult ? "" : ((String) fieldResult);
		String code = db.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			this.log(db.getMsg());
		}
		this.setErrCode(code);
		if (!StrTool.isBlankStr(str) && EncryptHelper.encryptSysParam.contains(paramName)) {
			str = EncryptUtils.decodeSave(str);
		}
		return str;
	}

	/**
	 * 根据paramName跟paramType查询对象
	 *
	 * @param paramName
	 * @param paramType
	 * @return
	 */
	public DicParam getParamByNameAndType(String paramName, int paramType) {
		String sql = "select * from dic_param where paramName=? ";

		Object[] params;// = {paramName, paramType};
		if (paramType == 1 || paramType == 3){
			sql += " and paramType=? and agentId=? ";
			params = new Object[] {paramName, paramType, CloudContextUtils.getAgentId()};
		} else {
			//兼容下级代理平台查前端界面查找2，实际为3的代理个性化参数
			sql += " and ((paramType=3 and agentId=?) or (paramType=2 and agentId=0 and paramName not in (select paramName from dic_param where agentId=? and paramType!=2))) ";
			params = new Object[] {paramName, CloudContextUtils.getAgentId(), CloudContextUtils.getAgentId()};
		}

		DicParam dicParam = db.queryForBean(sql, DicParam.class, params);
		String code = db.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			this.log(db.getMsg());
		}
		if (null != dicParam && EncryptHelper.encryptSysParam.contains(dicParam.getParamName()) && !StrTool.isBlankStr(dicParam.getParamValue())) {
			dicParam.setParamValue(EncryptUtils.decodeSave(dicParam.getParamValue()));
		}
		this.setErrCode(code);
		return dicParam;
	}


	//to add new record to database by bean
	public int addDicParam(String paramName, String paramValue, int paramType) {
		if (EncryptHelper.encryptSysParam.contains(paramName) && !StrTool.isBlankStr(paramValue)) {
			paramValue = EncryptUtils.encodeSave(paramValue);
		}
		String sql = "insert into dic_param(paramName, paramValue, paramType, agentId)" +
				"values(?,?,?,?);";
		Object[] params = {paramName, paramValue, paramType, CloudContextUtils.getAgentId()};
		int ret = db.executeSql(sql, params);
		String code = db.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			this.log(db.getMsg());
		}
		this.setErrCode(code);
		return ret;
	}

	//to add new record to database by map
	public int addDicParam(Map<String, Object> values) {
		//if (!values.containsKey("agentId")) {
			values.put("agentId", CloudContextUtils.getAgentId());
		//}
		int ret = db.insertRecord("dic_param", values);
		String code = db.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			this.log(db.getMsg());
		}
		this.setErrCode(code);
		return ret;
	}

	/**
	 * 新增param参数，agentId通过传值赋值
	 * @param values
	 * @return
	 */
	public int newDicParam(Map<String, Object> values) {
		if (!values.containsKey("agentId")) {
			values.put("agentId", CloudContextUtils.getAgentId());
		}
		int ret = db.insertRecord("dic_param", values);
		String code = db.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			this.log(db.getMsg());
		}
		this.setErrCode(code);
		return ret;
	}

	//to delete table record by id
	public int delDicParam(int id) {
		String sql = "delete from dic_param where id=? and agentId=?";
		int ret = db.executeSql(sql, new Object[]{id, CloudContextUtils.getAgentId()});
		String code = db.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			this.log(db.getMsg());
		}
		this.setErrCode(code);
		return ret;
	}

	//to delete table record by cdt
	public int delDicParam(Map<String, Object> cdt) {
		//if (!cdt.containsKey("agentId")) {
			cdt.put("agentId", CloudContextUtils.getAgentId());
		//}
		int ret = db.deleteRecord("dic_param", cdt);
		String code = db.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			this.log(db.getMsg());
		}
		this.setErrCode(code);
		return ret;
	}

	//to modify table record by values and condition
	public int modDicParam(Map<String, Object> values, Map<String, Object> cdt) {
		//if (!cdt.containsKey("agentId")) {
			cdt.put("agentId", CloudContextUtils.getAgentId());
		//}
		int ret = db.modifyRecord("dic_param", values, cdt);
		String code = db.getErrCode();
		this.setErrCode(code);
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			this.log(db.getMsg());
		}

		return ret;
	}

	//to query dic_param item for detail
	public DicParam queryDicParam(int id) {
		String sql = "select * from dic_param where id=? and agentId=?";
		DicParam ret = db.queryForBean(sql, DicParam.class, new Object[]{id, CloudContextUtils.getAgentId()});
		String code = db.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			this.log(db.getMsg());
		}
		this.setErrCode(code);
		if (null != ret && !StrTool.isBlankStr(ret.getParamValue()) && EncryptHelper.encryptSysParam.contains(ret.getParamName())) {
			ret.setParamValue(EncryptUtils.decodeSave(ret.getParamValue()));
		}
		return ret;
	}

	//to query DicParam record count
	public int queryDicParam(Map<String, Object> cdt) {
		//if (!cdt.containsKey("agentId")) {
			cdt.put("agentId", CloudContextUtils.getAgentId());
		//}
		int ret = db.queryRecordCount("dic_param", cdt);
		this.setErrCode(db.getErrCode());
		return ret;
	}

	//to query DicParam for record list with condition,if page or pagesize less than 0, means without pageuser_service
	public List<DicParam> queryDicParamList(Map<String, Object> cdt, int page, int pagesize) {
		//if (!cdt.containsKey("agentId")) {
			cdt.put("agentId", CloudContextUtils.getAgentId());
		//}
		List<DicParam> ret = db.queryForBeans("dic_param", "*", "id desc", DicParam.class, cdt, page, pagesize);
		String code = db.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			this.log(db.getMsg());
		}
		this.setErrCode(code);

		if (null != ret) {
			ret.forEach(item -> {
				if (!StrTool.isBlankStr(item.getParamName()) && EncryptHelper.encryptSysParam.contains(item.getParamName())) {
					item.setParamValue(EncryptUtils.decodeSave(item.getParamValue()));
				}
			});
		}

		return ret;
	}

	//to query dic_param item for detail
	public DicParam qryDicParams(Map<String, Object> cdt) {
		StringBuilder sql = new StringBuilder("select * from dic_param where 1=1 ");
		List<Object> params = new ArrayList<>();
		this.whereBuilderDept(cdt, sql, params);
		DicParam ret = db.queryForBean(sql.toString(), DicParam.class, params.toArray());
		String code = db.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			this.log(db.getMsg());
		}
		this.setErrCode(code);
		if (null != ret && !StrTool.isBlankStr(ret.getParamValue()) && EncryptHelper.encryptSysParam.contains(ret.getParamName())) {
			ret.setParamValue(EncryptUtils.decodeSave(ret.getParamValue()));
		}
		return ret;
	}

	private void whereBuilderDept(Map<String, Object> cdt, StringBuilder sql, List<Object> params){
		if(cdt.containsKey("id")){
			sql.append(" and id=? ");
			params.add(cdt.get("id"));
		}
		if(cdt.containsKey("paramName")){
			sql.append(" and paramName=? ");
			params.add(cdt.get("paramName"));
		}
		if(cdt.containsKey("paramValue")){
			sql.append(" and paramValue=? ");
			params.add(cdt.get("paramValue"));
		}
		if(cdt.containsKey("paramType")){
			sql.append(" and paramType=? ");
			params.add(cdt.get("paramType"));
		}
		if(cdt.containsKey("agentId")){
			sql.append(" and agentId=? ");
			params.add(cdt.get("agentId"));
		}
	}


	/**
	 * 通过name与属性查询数值
	 *
	 * @param paramName
	 * @return
	 */
	public String getParamValueByAgentIdAndParamName(String paramName, int agentId) {
		String sql = "select paramValue from dic_param where paramName=? and ((agentId=? and (paramType=1 or paramType=3)) or paramType=2) ";
		Object[] params = {paramName, agentId};
		Object fieldResult = db.queryFieldValue(sql, String.class, params, 1);
		String str = null == fieldResult ? "" : ((String) fieldResult);
		String code = db.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			this.log(db.getMsg());
		}
		this.setErrCode(code);
		if (!StrTool.isBlankStr(str) && EncryptHelper.encryptSysParam.contains(paramName)) {
			str = EncryptUtils.decodeSave(str);
		}
		return str;
	}

	/**
	 * 更新系统配置参数
	 *
	 * @param paramValue
	 * @param paramName
	 * @param paramType
	 * @return
	 */
	public int uptDicParam(String paramValue, String paramName, int paramType, boolean isUseAgentId) {
		if (EncryptHelper.encryptSysParam.contains(paramName) && !StrTool.isBlankStr(paramValue)) {
			paramValue = EncryptUtils.encodeSave(paramValue);
		}
		String sql = "update dic_param set paramValue=? where paramName=? and paramType=? ";
		Object[] params = {paramValue, paramName, paramType};
		if (isUseAgentId) {
			if (paramType == 1 || paramType == 3) {
				sql += " and agentId=? ";
				params = CObjectTool.objectArrAddValue(params, CloudContextUtils.getAgentId());
			}
		}
		int ret = db.executeSql(sql, params);
		String code = db.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			this.log(db.getMsg());
		}
		this.setErrCode(code);
		return ret;
	}
}